/**
 * 
 */
package it.irondev.appturismo.service.impl;

import it.irondev.appturismo.dao.AttractionsMapper;
import it.irondev.appturismo.dao.example.AttractionsExample;
import it.irondev.appturismo.dao.example.AttractionsExample.Criteria;
import it.irondev.appturismo.entity.Attractions;
import it.irondev.appturismo.filter.BaseFilter;
import it.irondev.appturismo.service.IAttractionService;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author federicocerruto
 *
 */
@Service
public class AttractionServiceImpl implements IAttractionService {

	@Autowired
	AttractionsMapper attractionDao;
	
	
	/* (non-Javadoc)
	 * @see it.irondev.appturismo.service.IAttractionService#getAttractionById(java.lang.Integer)
	 */
	public Attractions getAttractionById(Integer idAttraction) {
		return attractionDao.selectByPrimaryKey(idAttraction);
	}

	/* (non-Javadoc)
	 * @see it.irondev.appturismo.service.IAttractionService#getAllAttractions()
	 */
	public List<Attractions> getAllAttractions() {
		return attractionDao.selectByExample(null);
	}

	/* (non-Javadoc)
	 * @see it.irondev.appturismo.service.IAttractionService#addAttraction(it.irondev.appturismo.entity.Attractions)
	 */
	public void addAttraction(Attractions attraction) {
		attractionDao.insert(attraction);
	}

	/* (non-Javadoc)
	 * @see it.irondev.appturismo.service.IAttractionService#updateAttraction(it.irondev.appturismo.entity.Attractions)
	 */
	public void updateAttraction(Attractions attraction) {
		attractionDao.updateByPrimaryKeySelective(attraction);
	}

	/* (non-Javadoc)
	 * @see it.irondev.appturismo.service.IAttractionService#deleteAttraction(java.lang.Integer)
	 */
	public void deleteAttraction(Integer idAttraction) {
		attractionDao.deleteByPrimaryKey(idAttraction);
	}

	public List<Attractions> getAttractionsByFilter(final BaseFilter filter) {
		AttractionsExample example = null;
		if(filter!=null) {
			example = new AttractionsExample();
			Criteria criteria = example.createCriteria();
			if(filter.getId()!=null)
				criteria.andIdattractionEqualTo(filter.getId());
			if(filter.getIdlanguage()!=null)
				criteria.andLanguageEqualTo(filter.getIdlanguage());
			example.or(criteria);
		}
		List<Attractions> attractions = attractionDao.selectByExample(example);
		if(filter!=null && filter.getFavouriteCity()!=null)
			Collections.sort(attractions, new Comparator<Attractions>() {
				public int compare(Attractions o1, Attractions o2) {
					if(o1.getCity().getIdcity().equals(filter.getFavouriteCity()))
						return -1;
					if(o2.getCity().getIdcity().equals(filter.getFavouriteCity()))
						return 1;
					else return 0;
				}
				
			});
		return attractions;
	}

}
